import Crypto from '@/utils/crypto.js'
import '@/utils/hmac.js'
import '@/utils/sha1.js'
import { Base64 } from '@/utils/base64.js'
//  oss 配置
var uploadFileSize = 1024 * 1024 * 100 // 上传文件的大小限制100m
var policyText = {
  expiration: '2022-01-01T12:00:00.000Z', // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
  conditions: [
    ['content-length-range', 0, uploadFileSize], // 设置上传文件的大小限制
  ],
}
var policyBase64 = Base64.encode(JSON.stringify(policyText))
var message = policyBase64
var timetamp = new Date().getTime()

function randomString(len) {
  len = len || 32
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  var maxPos = chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}
const getSignature = function (policyBase64, env) {
  const accesskey = env.callback
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true,
  })
  const signature = Crypto.util.bytesToBase64(bytes)
  return signature
}
export default {
  data() {
    return {
      oss_info: '',
    }
  },
  methods: {
    /**
     * OSS-STS-令牌
     */
    async getOssStsToken() {
      const res = await this.$api.common.system('getpolicy')
      if (res.code === 0) {
        this.oss_info = res.data
      }
    },
    // 文件上传
    async fileUpload(type, path, name, fn) {
      let file_name = ''
      // #ifdef H5
      file_name = name
      // #endif
      // #ifdef MP-WEIXIN||APP-PLUS
      let arr = path.split('/')
      file_name = arr[arr.length - 1]
      // #endif
      console.log(file_name)
      let self = this
      await self.getOssStsToken()
      let sign = self.oss_info
      let oss = {
        Filename: `${sign.filename}`,
        key: `${sign.dir}${sign.filename}`,
        policy: sign.policy,
        OSSAccessKeyId: sign.accessid,
        signature: sign.signature,
        success_action_status: '200',
      }
      uni.showLoading({
        title: '文件上传中',
      })
      uni.uploadFile({
        url: sign.host,
        filePath: path,
        fileType: type,
        name: 'file',
        formData: {
          ...oss,
        },
        success: (res) => {
          console.log('uploadImage success, res is:', res)
          uni.hideLoading()
          uni.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 1000,
          })
          const file_url = `${sign.host}/${sign.dir}${sign.filename}`
          fn(file_url)
        },
        fail: (err) => {
          console.log('upload fail', err)
          uni.hideLoading()
          uni.showModal({
            content: err.errMsg,
            showCancel: false,
          })
        },
      })
    },
  },
}
